<template>
	<div class="icons" v-show="visiable" @click="handleScrollTop">
		<icon-caret-up size="2rem" class="icon" />
		<p class="text">返回顶部</p>
	</div>
</template>

<script setup>
const scrollTop = ref('')
const visiable = ref(false)
// 检测距离
function handleScroll() {
	scrollTop.value =
		window.pageYOffset ||
		document.documentElement.scrollTop ||
		document.body.scrollTop
	scrollTop.value > 500 ? (visiable.value = true) : (visiable.value = false)
}
let done = false
// 动画帧函数
function step() {
	scrollTop.value <= 0 ? (done = true) : (done = false)
	window.scrollTo({
		top: (scrollTop.value -= 15)
	})
	if (!done) {
		window.requestAnimationFrame(step)
	}
}
// 返回顶部
function handleScrollTop() {
	// 下一次重绘之前更新动画帧所调用的函数 60次1秒
	// https://developer.mozilla.org/zh-CN/docs/Web/API/Window/requestAnimationFrame
	window.requestAnimationFrame(step)
}
// 设置监听与卸载
onMounted(() => {
	window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
	window.removeEventListener('scroll', handleScroll)
})
</script>

<style lang="scss" scoped>
.icons {
	position: fixed;
	right: 3rem;
	bottom: 9rem;
	width: 2rem;
	height: 2rem;
	padding: var(--normal-sm-distance);
	background-color: #2c3e50;
	box-shadow: 0px 3px 3px rgb(133, 133, 133);
	cursor: pointer;
}
.icons > .icon {
	color: #1abc9c;
}
.icons > .text {
	display: none;
	font: bold 100% Consolas, Monaco, monospace;
	margin: 0;
	text-align: center;
	color: #2980b9;
}
.icons:hover > .text {
	display: block;
}
.icons:hover > .icon {
	display: none;
}
</style>
